package com.haier.uos.weather.data.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.haier.uos.weather.data.service.IWeatherDataService;
import com.haier.uos.weather.data.vo.WeatherResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class WeatherDataServiceImpl implements IWeatherDataService {
    private static final String BASE_URI = "http://wthrcdn.etouch.cn/weather_mini";
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public WeatherResponse getByCityId(String cityId) {
        String uri = BASE_URI + "?citykey=" + cityId;
        return getWeatherResponse(uri);
    }

    @Override
    public WeatherResponse getByCityName(String cityName) {
        String uri = BASE_URI + "?city=" + cityName;
        return getWeatherResponse(uri);
    }

    private WeatherResponse getWeatherResponse(String uri) {
        WeatherResponse weatherResponse = null;
        if (stringRedisTemplate.hasKey(uri)) {
            String string = stringRedisTemplate.opsForValue().get(uri);
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                weatherResponse = objectMapper.readValue(string, WeatherResponse.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            throw new RuntimeException("not has data to redis");
        }
        return  weatherResponse;
    }
}
